package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.entity.Authority
import com.zxy.supplier_system.server.entity.MarketSaleDocument
import com.zxy.supplier_system.server.service.MarketSaleDocumentService
import com.zxy.supplier_system.server.utils.IntIdAndName
import com.zxy.supplier_system.server.utils.toIntIdAndName
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.InputStreamResource
import org.springframework.core.io.Resource
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.web.bind.annotation.*
import java.math.BigDecimal
import java.time.OffsetDateTime

@RestController
@RequestMapping("markets/accounts/saleDocuments")
class MarketSaleDocumentController(
    private val marketSaleDocumentService: MarketSaleDocumentService,
    @Value("classpath:excel/templates/导入卖场户头销售模板.xlsx")
    private val resource: Resource,
) {

    class QueryMarketSaleDocumentRequest(
        val marketIds: List<Int> = emptyList(),
        val createdByIds: List<Int> = emptyList(),
        val status: MarketSaleDocument.Status?,
        val startYear: Int?,
        val startMonth: Int?,
        val endYear: Int?,
        val endMonth: Int?,
    )

    @HasAuthority(Authority.卖场_销售单_查询)
    @GetMapping
    fun queryMarketSaleDocument(
        queryMarketSaleDocumentRequest: QueryMarketSaleDocumentRequest,
        pageable: Pageable
    ): Page<QueryMarketSaleDocumentResponse> {
        return this.marketSaleDocumentService.queryMarketSaleDocument(queryMarketSaleDocumentRequest, pageable)
    }

    data class QueryMarketSaleDocumentResponse(
        val id: Long,
        val createdBy: IntIdAndName,
        val createdDateTime: OffsetDateTime,
        val goodsKindAmount: Int,
        val market: IntIdAndName,
        val status: MarketSaleDocument.Status,
        val month: Int,
        val year:Int,
    )

    data class UpdateOrderGoodsRequest(
        val goodsList: List<OrderGoodsItem>
    )

    data class OrderGoodsItem(
        val id: Int,
        val amount: Int
    )

    @HasAuthority(Authority.卖场_销售单_修改)
    @PatchMapping("{id}/goods")
    fun updateOrderGoods(
        @RequestBody updateOrderGoodsRequest: UpdateOrderGoodsRequest, @PathVariable id: Long,
    ) {
        return this.marketSaleDocumentService.updateOrderGoods(id, updateOrderGoodsRequest)
    }

    @HasAuthority(Authority.卖场_销售单_查询)
    @GetMapping("{id}")
    fun getMarketSaleDocumentDetail(@PathVariable id: Long, includeItems: Boolean = false): MarketSaleDocumentDetail {
        return this.marketSaleDocumentService.getMarketSaleDocumentDetail(id, includeItems)
    }

    data class MarketSaleDocumentDetail(
        val id: Long,
        val createdDateTime: OffsetDateTime,
        val createdBy: IntIdAndName,
        val market: IntIdAndName,
        val items: List<MarketSaleDocumentItemResponse>,
        val submittedDateTime: OffsetDateTime?,
        val auditedDateTime: OffsetDateTime?,
        val month:Int,
        val year:Int,
        val account:IntIdAndName,
        val note:String?
    ){
        companion object{
            fun fromMarketSaleDocument(marketSaleDocument: MarketSaleDocument,includeItems: Boolean = true): MarketSaleDocumentDetail {
                return MarketSaleDocumentDetail(
                    marketSaleDocument.id,
                    marketSaleDocument.createdDateTime,
                    IntIdAndName(marketSaleDocument.createdBy.id!!, marketSaleDocument.createdBy.name),
                    IntIdAndName(marketSaleDocument.market.id, marketSaleDocument.market.name),
                    if (!includeItems) emptyList() else marketSaleDocument.goodsList.map { item ->
                        val goods = item.goods
                        goods.let { it ->
                            MarketSaleDocumentItemResponse(
                                it.id,
                                it.name, it.barcode,
                                it.price,
                                it.amount,
                                it.createdDateTime,
                                it.lastModifiedDateTime,
                                it.brand?.toIntIdAndName(),
                                it.category?.toIntIdAndName(),
                                it.factory?.toIntIdAndName(),
                                item.amount,
                                it.boxSpecification,
                                item.totalFee,
                            )
                        }
                    },
                    marketSaleDocument.submittedDateTime,
                    marketSaleDocument.auditedDateTime,
                    marketSaleDocument.month,
                    marketSaleDocument.year,
                    marketSaleDocument.account.let { it ->
                        IntIdAndName(it.id!!, it.name)
                    },
                    marketSaleDocument.note,
                )
            }
        }
    }

    data class MarketSaleDocumentItemResponse(
        val id: Int,
        val name: String,
        val barcode: String,
        val price: BigDecimal,
        val amount: Int,
        val createdDateTime: OffsetDateTime,
        val lastModifiedDateTime: OffsetDateTime?,
        val brand: IntIdAndName?,
        val category: IntIdAndName?,
        val factory: IntIdAndName?,
        val amountInOrder: Int,
        val boxSpecification: String?,
        val totalFee:BigDecimal,

    )

    @HasAuthority(Authority.卖场_销售单_查询)
    @GetMapping("createdBys", params = ["projection=summary"])
    fun getMarketSaleDocumentCreatedEmployees(): List<IntIdAndName> {
        return this.marketSaleDocumentService.getAllEmployees()
    }


    @HasAuthority(Authority.卖场_销售单_开单)
    @PatchMapping("{id}/submit")
    fun submitOrder(@PathVariable id: Long) {
        return this.marketSaleDocumentService.submitMarketSaleDocument(id)
    }

    @HasAuthority(Authority.卖场_销售单_审核)
    @PatchMapping("{id}/audit")
    fun validate(@PathVariable id: Long): Long {
        return this.marketSaleDocumentService.audit(id).id
    }

    @DeleteMapping("{id}")
    fun deleteOrder(@PathVariable id: Long) {
        return this.marketSaleDocumentService.delete(id)
    }

    @HasAnyAuthority(Authority.卖场_销售单_修改,Authority.卖场_销售单_开单)
    @GetMapping("excel/import/template")
    fun exportTemplateForImport(): InputStreamResource {
        return InputStreamResource(resource.inputStream)
    }



}
